package com.graduation.springbootinit.controller;

import com.graduation.springbootinit.common.BaseResponse;
import com.graduation.springbootinit.common.ResultUtils;
import com.graduation.springbootinit.model.entity.ShopPart.AddressBook;
import com.graduation.springbootinit.model.entity.User;
import com.graduation.springbootinit.service.AddressBookService;
import com.graduation.springbootinit.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/shopPart/address")
public class AddressBookController {

    @Resource
    private AddressBookService addressBookService;

    @Resource
    private UserService userService;

    @PostMapping("/add")
    public BaseResponse<Void> save(@RequestBody AddressBook addressBook, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        addressBook.setUserId(loginUser.getId());
        return addressBookService.addAddress(addressBook);
    }

    @PostMapping("/setDefault")
    public BaseResponse<Void> setDefault(@RequestBody AddressBook addressBook, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        addressBookService.setDefault(addressBook.getId(), loginUser.getId());
        return ResultUtils.success(null);
    }

    @GetMapping("/default")
    public BaseResponse<AddressBook> getDefault(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        AddressBook address = addressBookService.getDefault(loginUser.getId());
        return ResultUtils.success(address);
    }

    @PostMapping("/get")
    public BaseResponse<AddressBook> get(@RequestBody AddressBook addressBook) {
        AddressBook address = addressBookService.getById(addressBook.getId());
        return ResultUtils.success(address);
    }

    @GetMapping("/list")
    public BaseResponse<List<AddressBook>> list(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        List<AddressBook> list = addressBookService.listByUserId(loginUser.getId());
        return ResultUtils.success(list);
    }

    @PostMapping("/update")
    public BaseResponse<Void> update(@RequestBody AddressBook addressBook, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        addressBook.setUserId(loginUser.getId());
        addressBookService.updateAddress(addressBook);
        return ResultUtils.success(null);
    }

    @PostMapping("/delete")
    public BaseResponse<Void> delete(@RequestBody AddressBook addressBook) {
        addressBookService.deleteAddress(addressBook.getId());
        return ResultUtils.success(null);
    }
} 